﻿using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using WeBlog.Interfaces;
using WeBlog.Models;

namespace WeBlog.Repositories
{    
    public class UserRepository : RepositoryBase<User>
    {
        public UserRepository(IUnitOfWork unitOfWork) : base( unitOfWork )
        {            
        }               

        public User FindByEmail( string email )
        {
            return FindAll().SingleOrDefault(x => x.Email == email);
        }
        
        public IEnumerable<User> FindAuthors()
        {
            return FindUsersInRoles(Role.Admin, Role.Author, Role.Editor);
        }

        public IQueryable<User> FindByRole(string roleName)
        {
            var role = RoleRepository.FindByName(roleName);
            return FindAll().Where(x => x.RoleFlag == role.RoleValue);
        }
        
        public MailAddressCollection FindEmailsByRole( params string[] roles )
        {
            var users = FindUsersInRoles(FindAll(), roles);
            var collection = new MailAddressCollection();
            users.ToList().ForEach( x => collection.Add(new MailAddress( x.Email, x.FullName )));
            return collection;
        }

        public IEnumerable<User> FindUsersInRoles(params string[] rolenames)
        {
            return FindUsersInRoles(FindAll().ToList(), rolenames);
        }

        public IEnumerable<User> FindUsersInRoles( IEnumerable<User> superset, params string[] rolenames)
        {
            var list = new List<User>();

            foreach (string role in rolenames)
            {
                list.AddRange(superset.Where(x => x.IsInRole(role) == true));
            }

            return list.Distinct().OrderBy(x => x.LastName).OrderBy(x => x.FirstName).ToList();
        }
    }
}
